<template>
  <div class="bg-white sticky top-0 z-10">
    <ul
      class="relative flex overflow-x-auto p-1 text-sm text-zinc-600 dark:bg-zinc-900 overflow-hidden"
      ref="ulTarget"
    >
      <!-- 滑动模块 -->
      <li
        ref="sliderTarget"
        class="absolute h-[27px] bg-zinc-900 dark:bg-zinc-800 rounded-lg duration-200"
        :style="sliderStyle"
      ></li>
      <li
        class="z-20 fixed top-0 right-[-1px] h-4 px-1 flex item-center justify-center bg-white shadow-l-white dark:shadow-l-zinc mt-1.5 dark:bg-zinc-900"
      >
        <m-svg-icon
          @click="isOpenPopup = !isOpenPopup"
          class="w-1.5 h-1.5"
          name="hamburger"
        />
      </li>
      <li
        v-for="(item, index) in $store.getters.categorys"
        :key="item.id"
        :ref="setItemRef"
        @click="onItemClick(item)"
        :class="{
          'text-zinc-100 ': $store.getters.currentCategoryIndex === index
        }"
        class="shrink-0 px-1.5 py-0.5 z-10 duration-200 last:mr-4"
      >
        {{ item.name }}
      </li>
    </ul>
    <m-popup v-model="isOpenPopup">
      <Menu @onItemClick="onItemClick" />
    </m-popup>
  </div>
</template>

<script setup>
import { ref, watch, onBeforeUpdate } from 'vue'
import { useScroll } from '@vueuse/core'
import Menu from '../../menu/index.vue'
// defineProps({
//   data: {
//     type: Array,
//     required: true
//   }
// })
const isOpenPopup = ref(false)
// 滑块
const sliderStyle = ref({
  transform: 'translateX(0px)',
  width: '54px'
})
// 选中的 item 下标
const currentCategoryIndex = ref(0)
// 获取填充的所有 item 元素
let itemRefs = []
const setItemRef = (el) => {
  if (el) {
    itemRefs.push(el)
  }
}
onBeforeUpdate(() => {
  itemRefs = []
})
// 获取 ul 元素，以计算偏移位置
const ulTarget = ref(null)
const { x: ulScrollLeft } = useScroll(ulTarget)
watch(currentCategoryIndex, (val) => {
  // 获取选中元素的 left、width
  const { left, width } = itemRefs[val].getBoundingClientRect()
  // 为 sliderStyle 设置属性
  sliderStyle.value = {
    // ul 横向滚动位置 + 当前元素的 left 偏移量
    transform: `translateX(${ulScrollLeft.value + left - 10 + 'px'})`,
    width: width + 'px'
  }
})
// item 点击事件
const onItemClick = (item) => {
  store.commit('app/changeCurrentCategory', item)
  isOpenPopup.value = false
}
</script>

<style lang="scss" scoped></style>
